from django.template import Node
from django.template import Library,VariableDoesNotExist,TemplateSyntaxError,resolve_variable
from django.conf import settings
from django.utils.translation import gettext_lazy as _
from django.core.urlresolvers import reverse

register = Library()

class HrefNode(Node):
	def __init__(self,view,argFuncs):
		self.view = view
		self.argFuncs = argFuncs
	def render(self,context):
		view = resolve_variable(self.view,context)
		if view == "":
			view = context["ham_view"]
			args = context["ham_args"]
			kwargs = context["ham_kwargs"]
		else:
			args = []
			kwargs = {}
		#try:
		for f in self.argFuncs:
			res = f(context)
			if type(res) == type([]):
				args += res
			elif type(res) == type({}):
				kwargs.update(res)
		#except VariableDoesNotExist:
		return reverse(view,None,tuple(args),kwargs)


@register.tag
def href(parser, token):
	"""Gets URL for given string with given arguments and saves it to url_for in context

	Usage:
		{% href "pacs.contest.views.show_contest" id=10,page=prev %}
	You can use '*', for variables given to current view.
	For example:
		{% href "pacs.contest.views.show_contest" id=*,page=prev %}
		{% href "foo.bar" *,*,7 %}
	Setting view to "" makes us use current view, and default append all current variables.
	For examle:
		{% href "" %}
	is always href to current view, with needed args. Defined kwargs mask current.
	"""
	bits = list(token.split_contents())
	view = bits[1]
	args = "".join(bits[2:]).split(',')
	if len(args) == 1 and args[0] == "":
		args = []
	def get_func(argToken,hamArgCounter=0):
		"""Returns function, that gets needed argument from context and returns one element list (arg) or dict (kwarg)"""
		c = argToken.count('=')
		if c>1:
			raise TemplateSyntaxError, "Possible args: 7,arg=7. Please no double equation marks."
		elif c==1:	#kwarg
			arg,val = argToken.split('=')
			if val == '*':
				return lambda context,arg=arg:{arg:context["ham_kwargs"][arg]}
			else:
				return lambda context,arg=arg,val=val:{arg:resolve_variable(val, context)}
		else:		#arg
			if argToken == '*':
				f = lambda context,c=hamArgCounter:[context["ham_args"][c]]
				hamArgCounter += 1
				return f
			else:
				return lambda context,val=argToken:[resolve_variable(val,context)]
	return HrefNode(view,map(get_func,args))

#class FurlNode(Node):
#	def __init__(self,args):
#		self.args = args
#
#	def render(self, context):
#		pars = {}
#		for d in context.dicts:
#			try:
#				pars.update(d)
#			except ValueError:
#				for dd in d.dicts:
#					pars.update(dd)
#		params = {}
#		params.update(context['ham_kwargs'])
##		def rev(x,*args,**kwargs):
#			params.update(kwargs)
#			return reverse(x,None,args,params)
#		pars['_reverse'] = rev
#		print "_reverse(%s)"%self.args
#		return eval("_reverse(%s)"%self.args,pars)
#def ohref(parser, token):
#	"""Gets URL for given string with given arguments and saves it to url_for in context
#
#	Usage:
#		{% href "pacs.contest.views.show_contest",id=10,page=prev %}
#	"""
#	comm = token.contents
#	args = comm[comm.find("href")+len("href"):]
#	return FurlNode(args)

@register.filter
def get_name(object,lang):
	try:
		return object.get_name(lang)
	except object.DoesNotExist:
		try:
			return object.get_name(settings.LANGUAGE_CODE)
		except object.DoesNotExist:
			return _("(Name in your language not found)")
